﻿using Autofac;
using Microsoft.Extensions.DependencyModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.Loader;
using XTemplate.Core.Attributes;

namespace XTemplate.Core.Model
{
    public class AutofacModule : Autofac.Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            var compilationLibrary = DependencyContext.Default
                .CompileLibraries
                .Where(x => !x.Serviceable && x.Type == "project")
                .ToList();
            var count1 = compilationLibrary.Count;
            List<Assembly> assemblyList = new List<Assembly>();

            foreach (var _compilation in compilationLibrary)
            {
                try
                {
                    assemblyList.Add(AssemblyLoadContext.Default.LoadFromAssemblyName(new AssemblyName(_compilation.Name)));
                }
                catch (Exception ex)
                {
                    Console.WriteLine(_compilation.Name + ex.Message);
                }
            }
            builder.RegisterAssemblyTypes(assemblyList.ToArray())
             .Where(type => (type.Name.EndsWith("Service") || type.Name.EndsWith("Repository"))
                 && !type.IsDefined(typeof(SkipInjectAttribute), false)
                 && !type.IsAbstract
                 && type.IsClass)
             .AsSelf()
             .AsImplementedInterfaces()
             .InstancePerLifetimeScope();

            var repository = assemblyList.Find(x => x.GetName().Name.EndsWith(".Repository"));
            if (repository != null)
            {
                var genericTypes = repository.DefinedTypes.Where(x => x.IsGenericType && !x.IsAbstract);
                foreach (var item in genericTypes)
                {
                    builder.RegisterGeneric(item);
                }
            }
        }
    }
}